import { find, instantiate, Node, Prefab, resources } from "cc";

export enum EDialog {
    UISetting = "UISetting",
    UISkillUpgrade = "UISkillUpgrade"
}
export class UIManager {

    public uiRoot: Node = null
    private Panels: Map<string, Node> = new Map() //以键值对访问时，Map比普通obj拥有更高的性能

    // 单例
    private static _instance: UIManager = null
    public static get instance() {
        if (!this._instance) this._instance = new UIManager()
        return this._instance
    }
    public openPanel(name: string, bringToTop = false) {

        if (!this.uiRoot) this.uiRoot = find("UIRoot") // 加载UIRoot
        if (this.Panels.has(name)) {
            let panel = this.Panels.get(name)
            if (bringToTop) {
                const index = this.uiRoot.children.length - 1 //把当前pannel放到最上层
                panel.setSiblingIndex(index)
            }
            panel.active = true
            return
        }

        resources.load("ui/prefabs/" + name, Prefab, (err: Error, data: Prefab) => {
            if (err) {
                console.log(err)
            } else {
                let panel = instantiate(data) //实例化
                this.Panels.set(name, panel) //收集
                this.uiRoot.addChild(panel)
            }
        })

    }
    public closePanel(name: string, destory = false) {
        if (!this.Panels.has(name)) return
        let panel = this.Panels.get(name)
        panel.active = false
        if (destory) {
            this.Panels.delete(name)
            panel.removeFromParent()
        }
    }


    public openDialog(name: string) {
        // 如果EDialog很长则耗费性能，可以用指针记录当前打开的对话框
        for (let dialog in EDialog) {
            if (dialog === name) {
                this.openPanel(name)
            } else {
                this.closePanel(dialog)
            }
        }
    }
    // 和panel不同,游戏中的对话框可能比较多，使用完毕后需要销毁
    public closeDialog(destory = false) {
        for (let dialog in EDialog) {
            this.closePanel(dialog, destory)
        }
    }
}